package study.springcloud.gateway.support.utils;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.Set;

@Slf4j
public final class RouteUtils {

    private RouteUtils() {
    }

    //==============================
    // 获取路由
    // ==============================

    /**
     * 获取路由
     */
    public static Route getRoute(ServerWebExchange exchange) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        return route;
    }

    //==============================
    // 网关请求服务 gateway --> service
    //==============================

    /**
     * URI
     */
    public static URI getGatewayRequestURI(ServerWebExchange exchange) {
        URI uri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        return uri;
    }

    /**
     * Path
     */
    public static String getGatewayRequestPath(ServerWebExchange exchange) {
        return getGatewayRequestURI(exchange).getPath();
    }

    /**
     * Host
     */
    public static String getGatewayRequestHost(ServerWebExchange exchange) {
        return getGatewayRequestURI(exchange).getHost();
    }

    //==============================
    // 客户端请求网关 client --> gateway
    //==============================

    /**
     * URI
     */
    public static URI getOriginalRequestURI(ServerWebExchange exchange) {
        Set<URI> uriSet = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        return CollectionUtil.getFirst(uriSet);
    }

    /**
     * Path
     */
    public static String getOriginalRequestPath(ServerWebExchange exchange) {
        return getOriginalRequestURI(exchange).getPath();
    }
}
